package com.insurance.pingan.bid.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 支付加密工具类
 * @version 1.0
 * @date 2020/9/27
 **/
public class SHA256Util {

    private static final String HEX_CHARS = "0123456789abcdef";
    private static final String SHA256 = "SHA-256";
    private static final String UTF8 = "UTF-8";

    /**
     * SHA256加密
     */
    public static String sha256LowerCase(String data) {
        try {
            return toHexString(sha256(data.getBytes(UTF8)));
        } catch (UnsupportedEncodingException e) {
            return null;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * SHA-256加密，并返回作为一个十六进制字节
     */
    private static byte[] sha256(byte[] data) throws NoSuchAlgorithmException {
        return getDigestBySha().digest(data);
    }

    /**
     * 返回 MessageDigest SHA-256
     */
    private static MessageDigest getDigestBySha() throws NoSuchAlgorithmException {
        return MessageDigest.getInstance(SHA256);
    }

    private static String toHexString(byte[] b) {
        StringBuffer stringbuffer = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            stringbuffer.append(HEX_CHARS.charAt(b[i] >>> 4 & 0x0F));
            stringbuffer.append(HEX_CHARS.charAt(b[i] & 0x0F));
        }
        return stringbuffer.toString();
    }

}
